class Solution {
public:
    bool check(int mid,vector<long long>& sum,vector<int>& nums,int k){
        int n = sum.size();
        long long ans = 0;
        for(int i = mid;i < n;i++){
            if(i == 0) return true;
            ans = (long long)nums[i-1] * mid - (sum[i] - sum[i-mid]);
            if(ans <= k){
                return true;
            }
        }
        return false;
    }
    int maxFrequency(vector<int>& nums, int k) {
        sort(nums.begin(),nums.end());
        int n = nums.size();
        
        vector<long long> sum(n+1);
        for(int i = 1;i <= n;i++){
            sum[i] = sum[i-1] + nums[i-1];
        }
        
        int l = 0;
        int r = n;
        while(l <= r){
            int mid = l + (r - l) / 2;
            if(check(mid,sum,nums,k)){
                l = mid+1;
            }else{
                r = mid-1;
            }
        }
        return r;
    }
};
